import pymysql
import asyncio

db_2m = {
    'host': 'rm-2zeqn1m3b6ik438mz.mysql.rds.aliyuncs.com',  # 主机
    'user': 'tanfeng',  # 用户名
    'password': 'Tf@654321',  # 密码
    'port': 3306,  # 端口 3306
    'database': 'ppg'  # 数据库名
}


async def main():
    # 连接2m库
    connection_2m = pymysql.connect(**db_2m)
    # 创建游标对象
    cursor_2m = connection_2m.cursor()
    try:
        # 从2m库中选择所有数据
        cursor_2m.execute(f"select owner_no,count(*)*500 from t_sku where `name`='VIP经验卡' and `status` in ('02') group by owner_no;")
        rows = cursor_2m.fetchall()
        for row in rows:
            owner_no = row[0]
            balance = row[1]
            sql_select = f"select balance from t_wallet where type='06' and account_no = %s limit 1;"
            data = owner_no
            cursor_2m.execute(sql_select, data)
            result = cursor_2m.fetchone()
            if result is not None:
                # 加经验值
                update_balance_sql = f"update t_wallet set balance=balance + %s where account_no = %s and type='06'"
                update_balance_data = (balance, owner_no)
                cursor_2m.execute(update_balance_sql, update_balance_data)
                # 销毁经验验卡
                update_vip_sql = f"update t_sku set status='102' where `name`='VIP经验卡' and status='02' and owner_no=%s"
                update_vip_data = owner_no
                cursor_2m.execute(update_vip_sql, update_vip_data)
                connection_2m.commit()
                print(f"{owner_no} update->{balance}")
            else:
                print(f"{owner_no} insert->{balance}")

        print("数据表导入成功！")
    except (pymysql.Error) as error:
        print("导入数据表时发生错误:", error)

    # 关闭游标和连接
    cursor_2m.close()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())